import { useEffect, useRef, useState } from "react";
import Button from "./Button";

type CountDownProps = {
  start: number;
  onDone?: () => void;
};

export default function CountDown({ start, onDone }: CountDownProps) {
  const [current, setCurrent] = useState(start);
  const intervalRef = useRef<number | null>(null);

  const countDown = () => {
    setCurrent(start);
    const i = setInterval(() => {
      setCurrent((prev) => {
        const newCurrent = Math.max(prev - 1, 0);
        if (newCurrent <= 0) {
          clearInterval(i);
          intervalRef.current = null;
          onDone?.();
        }
        return newCurrent;
      });
    }, 1000);

    intervalRef.current = i;
  };

  useEffect(() => {
    countDown();

    return () => {
      if (intervalRef.current !== null) {
        console.log("clear interval");
        clearInterval(intervalRef.current);
      }
    };
  }, []);

  return (
    <div>
      {current}
      {current <= 0 ? <Button onClick={countDown}>Reset</Button> : null}
    </div>
  );
}
